var bbd_id = page.getUrlParam("bbd_id");
var bb_id = page.getUrlParam("bb_id");
var empInfo = {};
var user_id = "";
var dateCalculate = new Array();
var zc_bb_id = "";
var bbd_cost_type = "NO";
//初始化时查询报销人下拉集
var jobMaps = "";
var positionList = "";
$(function () {
    //初始化城市控件
    //initCityCtrl();
    if ($("input[name='costor']").eq(0).attr("type") == "checkbox") {
        if (!$("input[name='costor']").eq(0).is(":checked")) {
            $("#wldwskTitle_container").hide();
            $("#BxGysInfoList_container").hide();
        }
        if (!$("input[name='costor']").eq(1).is(":checked")) {
            $("#ygskTitle_container").hide();
            $("#BxPersonCollectionInfoList_container").hide();
        }
        if (!$("input[name='costor']").eq(2).is(":checked")) {
            $("#yyryskTitle_container").hide();
            $("#BxYwryInfoList_container").hide();
        }
        if ($("input[name='costor']").eq(1).is(":checked")) {
            addDefaultYGSK();
        }
    } else {
        var costor = $("#costor").val();
        if (costor) {
            if (!costor.indexOf("01") > -1) {
                $("#wldwskTitle_container").hide();
                $("#BxGysInfoList_container").hide();
            }
            if (!costor.indexOf("02") > -1) {
                $("#ygskTitle_container").hide();
                $("#BxPersonCollectionInfoList_container").hide();
            }
            if (!costor.indexOf("03") > -1) {
                $("#yyryskTitle_container").hide();
                $("#BxYwryInfoList_container").hide();
            }
            if (costor.indexOf("02") > -1) {
                addDefaultYGSK();
            }
        } else {
            $("#wldwskTitle_container").hide();
            $("#BxGysInfoList_container").hide();
            $("#ygskTitle_container").hide();
            $("#BxPersonCollectionInfoList_container").hide();
            $("#yyryskTitle_container").hide();
            $("#BxYwryInfoList_container").hide();
        }
    }
    $("input[name='costor']").eq(0).click(function () {
        if ($(this).is(":checked") == true) {
            //选中触发事件
            $("#wldwskTitle_container").show();
            $("#BxGysInfoList_container").show();
            var danweiCtrl = $("#BxGysInfoList_appTable").children(".goOutBx")
            for (var i = 1; i < danweiCtrl.length; i++) {
                $("#BxGysInfoList_appTable").children(".goOutBx").eq(i).hide();
            }
        } else {
            //取消选中触发事件
            $("#wldwskTitle_container").hide();
            $("#BxGysInfoList_container").hide();
            var BxGysInfoTable = Form.getAppTablView("BxGysInfoList");
            if (BxGysInfoTable && deleteStatus) {
                var BxGysInfoList = BxGysInfoTable.getDataList();
                var json = {
                    "funName": "deletePaymentDetail",
                    "funType": "C",
                    "valMap": {
                        "bx_id": getBRAID(),
                        "object_type": "01"
                    }
                }
                var ret = webApi.ajax("common.deleteForm", json);
                BxGysInfoTable.rendTable();
                $("#btn_wl").text("0条");
            }
        }
    });
    $("input[name='costor']").eq(1).click(function () {
        if ($(this).is(":checked") == true) {
            //选中触发事件
            $("#ygskTitle_container").show();
            $("#BxPersonCollectionInfoList_container").show();
            addDefaultYGSK();
            var persionCtrl = $("#BxPersonCollectionInfoList_appTable").children(".goOutBx")
            for (var i = 1; i < persionCtrl.length; i++) {
                $("#BxPersonCollectionInfoList_appTable").children(".goOutBx").eq(i).hide();
            }
        } else {
            //取消选中触发事件
            $("#ygskTitle_container").hide();
            $("#BxPersonCollectionInfoList_container").hide();
            var BxPersonCollectionInfoTable = Form.getAppTablView("BxPersonCollectionInfoList");
            if (BxPersonCollectionInfoTable && deleteStatus) {
                var BxPersonCollectionInfoList = BxPersonCollectionInfoTable.getDataList();
                var payment_details_id = "";
                for (var i = 0; i < BxPersonCollectionInfoList.length; i++) {
                    payment_details_id = payment_details_id + BxPersonCollectionInfoList[i].payment_details_id + ",";
                }
                var json = {
                    "funName": "deletePaymentDetail",
                    "funType": "C",
                    "valMap": {
                        "bx_id": getBRAID(),
                        "object_type": "02"
                    }
                }
                var ret = webApi.ajax("common.deleteForm", json);
                BxPersonCollectionInfoTable.rendTable();
                $("#btn_yg").text("0条");
            }
        }
    });
    $("input[name='costor']").eq(2).click(function () {
        if ($(this).is(":checked") == true) {
            //选中触发事件
            $("#yyryskTitle_container").show();
            $("#BxYwryInfoList_container").show();
            var yuanwaiCtrl = $("#BxYwryInfoList_appTable").children(".goOutBx")
            for (var i = 1; i < yuanwaiCtrl.length; i++) {
                $("#BxYwryInfoList_appTable").children(".goOutBx").eq(i).hide();
            }
        } else {
            //取消选中触发事件
            $("#yyryskTitle_container").hide();
            $("#BxYwryInfoList_container").hide();
            var BxYwryInfoTable = Form.getAppTablView("BxYwryInfoList");
            if (BxYwryInfoTable && deleteStatus) {
                var BxYwryInfoDataList = BxYwryInfoTable.getDataList();
                var json = {
                    "funName": "deletePaymentDetail",
                    "funType": "C",
                    "valMap": {
                        "bx_id": getBRAID(),
                        "object_type": "03"
                    }
                }
                var ret = webApi.ajax("common.deleteForm", json);
                BxYwryInfoTable.rendTable();
                $("#btn_yyry").text("0条");
            }
        }
    });
    //员工收款
    var ygCtrl = $("#ygskTitle");
    if (ygCtrl && ygCtrl.length > 0) {
        $("#is_external_container").hide();
        $("#tu_id_container").hide();
        $("#tub_account_number_container").hide();
        $("#tub_type_container").hide();
        $("#tub_bank_container").hide();
        var titleHTMLYG = "";
        titleHTMLYG += "<p class='detailedTtitle' id='title_yg'>  员工收款信息</p>";
        var ygTableView = Form.getAppTablView("BxPersonCollectionInfoList");
        if (ygTableView) {
            var dataList = ygTableView.getDataList();
            if (dataList.length > 0) {
                titleHTMLYG += "<div class='detailedBtn' id='btn_yg' onclick='btnYGSK()'>" + dataList.length + "条</div>";
            } else {
                titleHTMLYG += "<div class='detailedBtn' id='btn_yg' onclick='btnYGSK()'>0条</div>";
            }
        }
        $("#ygskTitle").addClass("mui-input-row");
        $("#ygskTitle").append(titleHTMLYG);
    }
    //院外人员收款
    var yyryCtrl = $("#yyryskTitle");
    if (yyryCtrl && yyryCtrl.length > 0) {
        var titleHTMLYYRY = ""
        titleHTMLYYRY += "<p class='detailedTtitle' id='title_yyry'>  院外人员收款信息</p>";
        var yyryTableView = Form.getAppTablView("BxYwryInfoList");
        if (yyryTableView) {
            var dataList = yyryTableView.getDataList();
            if (dataList.length > 0) {
                titleHTMLYYRY += "<div class='detailedBtn' id='btn_yyry' onclick='btnYWRYSK()'>" + dataList.length + "条</div>";
            } else {
                titleHTMLYYRY += "<div class='detailedBtn' id='btn_yyry' onclick='btnYWRYSK()'>0条</div>";
            }
        }
        $("#yyryskTitle").addClass("mui-input-row");
        $("#yyryskTitle").append(titleHTMLYYRY);
    }
    //往来单位收款
    var wlCtrl = $("#wldwskTitle");
    if (wlCtrl && wlCtrl.length > 0) {
        var titleHTMLWL = ""
        titleHTMLWL += "<p class='detailedTtitle' id='title_wl'>  往来单位收款信息</p>";
        var wlTableView = Form.getAppTablView("BxGysInfoList");
        if (wlTableView) {
            var dataList = wlTableView.getDataList();
            if (dataList.length > 0) {
                titleHTMLWL += "<div class='detailedBtn' id='btn_wl' onclick='btnWLSK()'>" + dataList.length + "条</div>";
            } else {
                titleHTMLWL += "<div class='detailedBtn' id='btn_wl' onclick='btnWLSK()'>0条</div>";
            }
        }
        $("#wldwskTitle").addClass("mui-input-row");
        $("#wldwskTitle").append(titleHTMLWL);
    }
    $("#costor_container").find(".mui-checkbox").css({"margin-left": "10px", "padding-left": "2px"});
    $("#costor_container").find("input").attr("style", "left:22%!important;top:55%");
    var persionCtrl = $("#BxPersonCollectionInfoList_appTable").children(".goOutBx")
    for (var i = 1; i < persionCtrl.length; i++) {
        $("#BxPersonCollectionInfoList_appTable").children(".goOutBx").eq(i).hide();
    }
    var yuanwaiCtrl = $("#BxYwryInfoList_appTable").children(".goOutBx")
    for (var i = 1; i < yuanwaiCtrl.length; i++) {
        $("#BxYwryInfoList_appTable").children(".goOutBx").eq(i).hide();
    }
    var danweiCtrl = $("#BxGysInfoList_appTable").children(".goOutBx")
    for (var i = 1; i < danweiCtrl.length; i++) {
        $("#BxGysInfoList_appTable").children(".goOutBx").eq(i).hide();
    }
})

function addDefaultYGSK() {
    var BxPersonCollectionInfoTable = Form.getAppTablView("BxPersonCollectionInfoList");
    if (BxPersonCollectionInfoTable) {
        var BxPersonCollectionInfoList = BxPersonCollectionInfoTable.getDataList();
        if (BxPersonCollectionInfoList.length == 0) {
            var bhe_id = page.getCurrencyEmpInfo().bhe_id;
            var bb_id = $("bb_id").val();
            if (!bb_id) {
                if (page.isnotNull(zc_bb_id)) {
                    bb_id = zc_bb_id;
                } else {
                    zc_bb_id = page.getuuid();
                    bb_id = zc_bb_id;
                }
            }
            var data = {
                "payment_details_id": "{uuid}",
                "bx_bill_id": bb_id,
                "object_type": "02",
                "delete_flag": "0"
            };
            data.payment_method = getBillTypeInfo(getBBDID())["default_collection_method"];
            var json = {
                "funName": "BD_HR_EMPINFO",
                "funSystem": "bd",
                "valMap": {
                    "bhe_id": bhe_id
                }
            }
            var ret0 = webApi.ajax("common.queryForm", json);
            if (ret0 && ret0.status == "0" && ret0.result.data) {
                data.object_name = ret0.result.data.persion_name;
                data.object_id = bhe_id;
                data.payment_dept_id = ret0.result.data.jobs_in_dept;
                data.person_code = ret0.result.data.persion_code;
                data.user_mobile = ret0.result.data.persion_moddle_num;
                data.bank_of_deposit = ret0.result.data.bd_jobgouup59; // 开户行
                data.bank_card_no = ret0.result.data.jobs_wagesnum; // 银行卡号
                var jsone = {
                    "funName": "queryBankNumberListByBheId",
                    "valMap": {
                        "Bhe_Id": bhe_id
                    }
                }
                var ret = webApi.ajax("common.queryList", jsone);
                if (ret && ret.status == "0" && ret.result.data && ret.result.data.length > 0) {
                    for (var i = 0; i < ret.result.data.length; i++) {
                        if (ret.result.data[i].hr_group1 == '0') {
                            data.bank_card_no = ret.result.data[i].bank_number;//
                            if (!data.payment_method) {
                                data.payment_method = ret.result.data[i].bww_id;// 结算类型
                            }
                            data.bank_of_deposit = ret.result.data[i].bank_of_deposit;// 开户行
                            break;
                        }
                    }
                }
            }
            if (page.isnotNull(data.payment_method)) {
                var jsone = {
                    "funName": "BXQueryPaymentMethodName",
                    "valMap": {
                        "payment_method": data.payment_method
                    }
                }
                var ret1 = webApi.ajax("common.queryList", jsone);
                if (ret1 && ret1.status == "0" && ret1.result.data && ret1.result.data.length > 0) {
                    if (ret1.result.data[0].bww_name.indexOf("现金") > -1) {
                        data.bank_card_no = "";
                        data.bank_of_deposit = "";
                    }
                }
            }
            var json = {
                "funName": "BX_PAYMENT_DETAILS",
                "funSystem": "bx",
                "funDbType": "add",
                "valMap": data
            }
            var ret = webApi.ajax("common.submitForm", json);
            if (ret && ret.status == "0") {
                if (page.isnotNull(data.payment_dept_id)) {
                    var jsone = {
                        "funName": "BXQueryDeptName",
                        "valMap": {
                            "dept_id": data.payment_dept_id
                        }
                    }
                    var ret = webApi.ajax("common.queryList", jsone);
                    if (ret && ret.status == "0" && ret.result.data && ret.result.data.length > 0) {
                        data.show_payment_dept_id = ret.result.data[0].oname;
                    }
                }
                if (page.isnotNull(data.payment_method)) {
                    data.show_payment_method = ret1.result.data[0].bww_name;
                }
                BxPersonCollectionInfoTable.rendTable([data]);
                $("#btn_yg").text("1条")
            }
        }
    }
}

// 数据初始化
function formOnload() {
    disabledCtrl();
    // 页面控件控制
    controlCtrl();
    initDateCtrl();
    createButton();
    btnHide();
    addDetail();
    $("#apply_amount").val(getSaveApplyAmount());
}

function btnYGSK() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }


    // 新跳转方式
    var url = "/html/common/list.html?ListCode=addBxPersonCollectionInfoList";
    var data = {};//传参
    /**
     * @param url 跳转地址
     * @param data
     * @param function 回调方法
     * @refresh 旧页面是否刷新
     */
    page.openWindow(url, data, function () {
    }, true);
    //老跳转方式
    page.openWindow("/html/common/list.html?ListCode=addBxPersonCollectionInfoList&bra_id=" + bb_id + "&bbd_id="
        + getBBDID() + "&deleteStatus=" + deleteStatus);

}

function btnYWRYSK() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    page.openWindow("/html/common/list.html?ListCode=addBxYwryInfoList&bra_id=" + bb_id + "&bbd_id=" + getBBDID() + "&deleteStatus=" + deleteStatus);
}

function btnWLSK() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    page.openWindow("/html/common/list.html?ListCode=addBxGysInfoList&bra_id=" + bb_id + "&bbd_id=" + getBBDID() + "&deleteStatus=" + deleteStatus);

}

// 控件禁用
function disabledCtrl() {
    $("#apply_amount").attr("disabled", "disabled");
    $("#travel_days").attr("disabled", "disabled");
    $("#technical").attr("disabled", "disabled");
    $("#position").attr("disabled", "disabled");
    $("#costDetailTitle_container").css("overflow", "hidden");
    $("#appBxTravelPartnerList_container").css("overflow", "hidden");
    if ($("#gwJDDetail_container").length = 1) {
        $("#gwJDDetail_container").css("height", "30px");
    }
    if (!page.isnotNull(bb_id)) {
        //新增时
        $("#extend20_upload_button").attr("disabled", false);
        $("#user_id").val(empInfo.bhe_id);
        //$("#ca_user").val(empInfo.persion_name);
        initTeach(empInfo.bhe_id);
    }
    if (status == "YSP" || status == "SPZ") {
        if (FormData.is_submit_editfile != "1") {
            $("#extend20_upload_button").attr("disabled", "disabled");
            $("#extend20_upload_button").attr('style', "width:50px !important;background-color:#c6c6c6 !important;");
        }
    }
}

//弃审
function btn_abandonment() {
    var status = $("#status").val();
    var cost_share_list = new Array();
    if (status != "YSP") {
        dialogBox.showMessDialog("只有已审批状态单据才可以弃审！");
        return;
    }
    var business_type_code = getBillTypeInfo(bbd_id)['business_type_code'];
    var dataList = getYSZXDataList(bb_id, cost_share_list, business_type_code);
    if (!ysYZ(dataList)) {
        return;
    }
    stopFlowOfEnd();
}

//删除
function btn_delete() {
    var flag = $("#status").val();
    if (flag == "YTJ" || flag == "YSP" || flag == "SPZ") {
        dialogBox.showMessDialog("已提交,已审批,审批中状态的单据不可删除");
        return;
    }
    var data = Form.getAppFormData();
    var json = {};
    json = getMainData(data, json);
    json = getChildData(json);
    var ret = webApi.ajax("fim.AppBill.Delete", json);
    if (ret) {
        if (ret.status == "0") {
            dialogBox.showMessDialog("删除成功!");
            setTimeout(function () {
                mui.myback()
            }, 50)
        } else {
            dialogBox.showMessDialog("删除失败:" + ret.message);
        }
    } else {
        dialogBox.showMessDialog("网络异常，请联系管理员!");
    }
}

// 分摊方式
function getBbdCostType(bbd_id) {
    if (!page.isnotNull(bbd_id)) {
        //解决审批流中从url中获取不到bbd_id
        if (page.isnotNull($("#bb_id").val())) {
            var json2 = {
                "funName": "BX_BILL",
                "funSystem": "bx",
                "valMap": {
                    "bb_id": $("#bb_id").val()
                }
            }
            var ret2 = webApi.ajax("common.queryForm", json2);
            if (ret2 && ret2.status == "0" && ret2.result && ret2.result.data) {
                bbd_id = ret2.result.data.bbd_id;
            }
        }
    }
    return bbd_cost_type;
}

//预算预占/修改
function ysYZ(valList) {
    var flag = true;
    if (valList && valList.length > 0) {
        var json = {
            "method": "pre_occupy",
            "funSystem": "bx",
            "valList": valList
        }
        var ret = webApi.ajax("hcbm.budgetControl.budgetExcute", json);
        if (ret && ret.status == "0") {
            flag = true;
        } else {
            flag = false;
            dialogBox.showMessDialog(ret.message);
        }
    }
    return flag;
}

//获取预算执行明细
function getYSZXDataList(bb_id, cost_share_list, business_type_code) {
    var json = {
        "funName": "queryBcsdByBBIdAndCostType",
        "valMap": {
            "bb_id": bb_id,
            "bbd_cost_type": "CBMS"
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
        var dataList = ret.result.data;
        for (var i = 0; i < dataList.length; i++) {
            var cost_share_map = {};
            cost_share_map["budget_id"] = dataList[i].budget_id;
            cost_share_map["cbfl_formid"] = dataList[i].bb_id;
            cost_share_map["bcom_id"] = page.getCompanyId();
            cost_share_map["finalversion_id"] = dataList[i].finalversion_id; //预算号主键
            cost_share_map["cbfl_formbid"] = business_type_code;//业务类型ID
            cost_share_map["apply_psn"] = $("#user_id").val();//申请人
            cost_share_map["pre_all_num"] = $("#apply_amount").val();//执行金额
            cost_share_map["cbfd_id"] = "";//来源单据ID
            cost_share_map["cbfd_front"] = "";//来源单据号
            cost_share_list.push(cost_share_map);
        }
    }
    return cost_share_list;
}

//预算删除
function ysSC(valList, business_type_code) {
    var flag = true;
    if (valList && valList.length > 0) {
        var json = {
            "method": "delete",
            "funSystem": "bx",
            "org_id": page.getCompanyId(),
            "zx_num": $("#bb_id").val(),             //当前单据ID
            "zx_code": $("#bb_code").val(),  //当前单据code
            "cbfd_code": business_type_code,     //业务类型编码
            "cbfd_source": "",  //来源控制类型
            "applycode": "",    //预算申请单号
            "applyid": "",   //预算申请单ID
            "zx_date": enter_date,  //执行单据日期
            "cbfl_auditdate": approval_date,   //审核日期
            "cbfl_period": "",  //所属期间
            "is_apply": "",
            "valList": valList
        }
        var ret = webApi.ajax("hcbm.WBbudgetControl.WBbudgetExcute", json);
        if (ret && ret.status == "0") {
            flag = true;
        } else {
            flag = false;
            dialogBox.showMessDialog(ret.message);
        }
    }
    return flag;
}

//收回
function btn_takeback() {
    var mainId = bb_id ? bb_id : $("#bb_id").val();
    retrieve(mainId, null);
}

function btnHide() {
    var status = $("#status").val();
    $("#btn_save").hide();
    $("#btn_submit").hide();
    $("#btn_abandonment_bottom").hide();
    $("#btn_delete_bottom").hide();
    $("#btn_verify_bottom").hide();
    $("#btn_takeback_bottom").hide();
    $("#btnShowBraInfo_bottom").hide();
    $("#showTBZD_bottom").hide();
    $("#btn_abandonment").hide();
    $("#btn_delete").hide();
    $("#btn_verify").hide();
    $("#btn_takeback").hide();
    if (status == "ZC") {
        $("#btn_delete").show();
    } else if (status == "BC") {
        $("#btn_delete").show();
        $("#btn_submit").show();
    } else if (status == "YTJ") {
        $("#btn_takeback").show();
        $("#btn_verify").show();
    } else if (status == "SPZ") {
        $("#btn_verify").show();
    } else if (status == "YSP") {
        $("#btn_verify").show();
        $("#btn_abandonment").show();
    } else if (status == "YBH") {
        $("#btn_verify").show();
        $("#btn_delete").show();
    }
    if (!isLinkedBra) {
        $("#btnShowBraInfo").hide();
    }
    $("#user_id_container").hide();
    $("#btn_area").addClass("form-btn-2");
    $("#btn_area").removeClass("form-btn-3")
}

var isLinkedBra = false;
var deleteStatus = true;

function initFormData(data) {
    if (data) {
        empInfo = data.empInfo;
        bbd_cost_type = data.bbd_cost_type;//分摊类型
        jobMaps = page.isnotNull(data["jobMaps"]) ? data["jobMaps"] : [];
        positionList = page.isnotNull(data["positionList"]) ? data["positionList"] : [];

        if (data.bx_bill_link && data.bx_bill_link == "1") {
            isLinkedBra = true;
        }
        if (data.status != "ZC" && data.status != "BC") {
            deleteStatus = false;
        }
        var status = data.status;
        if (status == "YTJ" || status == "YSP" || status == "SPZ") {
            var btn_save = $($(".btn_save")[1]);
            if (btn_save && btn_save.length > 0) {
                $($(".btn_save")[1]).attr("disabled", "disabled");
                document.getElementsByClassName("btn_save")[1].style.backgroundColor = '#c6c6c6';
            }
        }
        if (status != "BC") {
            var btn_submitform = $($(".btn_submit")[1]);
            if (btn_submitform && btn_submitform.length > 0) {
                $($(".btn_submit")[1]).attr("disabled", "disabled");
                document.getElementsByClassName("btn_submit")[1].style.backgroundColor = '#c6c6c6';
            }
        }
        data.user_code = empInfo.persion_code;
    } else {
        data = {};
        data.user_code = empInfo.persion_code;
        var status = page.getUrlParam("status");
        if (status == "YTJ" || status == "YSP" || status == "SPZ") {
            var btn_save = $($(".btn_save")[1]);
            if (btn_save && btn_save.length > 0) {
                $($(".btn_save")[1]).attr("disabled", "disabled");
                document.getElementsByClassName("btn_save")[1].style.backgroundColor = '#c6c6c6';
            }
        }
        if (status != "BC") {
            var btn_submitform = $($(".btn_submit")[1]);
            if (btn_submitform && btn_submitform.length > 0) {
                $($(".btn_submit")[1]).attr("disabled", "disabled");
                document.getElementsByClassName("btn_submit")[1].style.backgroundColor = '#c6c6c6';
            }
        }
        user_id = empInfo.bhe_id
    }
    return data;
}

//主表数据
function getMainData(data, json) {
    if (!data.bb_id) {
        data.bb_id = zc_bb_id;
    }
    if (!page.isnotNull(data.bb_code)) {
        data.app_form_code = page.getUrlParam("formCode");
        data.delete_flag = "0";
        data.bx_bill_link = "0";
        data.entor = "{userid}";
        data.enter_date = "{strdatetime}";
        data.status = "BC";
        data.bb_code = page.getSerialNumber("BX_BILL_CODE", {});
    }
    data.status = "BC";
    data.position = "";
    data.user_name = data.ca_user;
    data.ca_user = "";
    data.technical = "";
    delete data["costDetailTitle"];
    delete data["costShareDetailTitle"];
    delete data["appBxTravelPartnerList"];
    delete data["costShareDetailTitleZX"];
    delete data["costShareDetailListZX"];
    delete data["costShareDetailList"];
    delete data["bxCostApplyEmpList"];
    delete data["costDetailList"];
    delete data["ywNewShareDetailList"];
    delete data["ygskTitle"];
    delete data["yyryskTitle"];
    delete data["wldwskTitle"];
    data.area = $("#area").attr("data-areaid");
    data.org_id = getORGID();
    if ($("#travel_tools").length > 0 && $("#travel_tools").val() == "-1") {
        dialogBox.alert("请选择交通工具！");
        return;
    }
    if ($("#train_type").length > 0 && $("#train_type").val() == "-1") {
        dialogBox.alert("请选择培训类型！");
        return;
    }
    if ($("#meeting_type").length > 0 && $("#meeting_type").val() == "-1") {
        dialogBox.alert("请选择会议类型！");
        return;
    }
    // 校验同行人
    // var bill_type_info = getBillTypeInfo(bbd_id);
    // if (!checkTravelPartner(data.bb_id, bbd_id, bill_type_info.is_check_travelpartner)) return;
    // data.apply_amount = getSaveApplyAmount();
    // if (!data.apply_amount) {
    //     data.apply_amount = "0.00";
    // }
    //
    // var data = Form.getAppFormData();
    // var ysTableView = Form.getAppTablView("ywNewShareDetailList");
    // if (ysTableView && ysTableView.getDataList().length > 0) {
    //     var saveResult = saveRefundBillYS(data);
    //     if (!saveResult) return;
    // }
    var array = [];
    array.push(data);
    json["BillVO"] = array;
    return json;
}

//预算分摊明细
function getChildData(json) {
    // 申请明细
    var detail = Form.getAppTablView("costDetailList_appTable");
    var detailList = detail.getDataList();
    if (!detailList || detailList.length <= 0) {
        detailList = [];
    }
    json["CostApplyDetailVO"] = detailList;

    var bxYsCostShareTable = Form.getAppTablView("costShareDetailList_appTable");
    var bxYsCostShareDataList = bxYsCostShareTable.getDataList();
    if (!bxYsCostShareDataList || bxYsCostShareDataList.length <= 0) {
        bxYsCostShareDataList = [];
    }
    json["CostShareDetailVO"] = bxYsCostShareDataList;
    var bxZxCostShareTable = Form.getAppTablView("costShareDetailListZX_appTable");
    var bxZxCostSharedataList = bxZxCostShareTable.getDataList();
    if (!bxZxCostSharedataList || bxZxCostSharedataList.length <= 0) {
        bxZxCostSharedataList = [];
    }
    json["CostShareDetailVO"] = bxZxCostSharedataList;
    return {"data": [json]};
}


function initSaveForm(data, state) {
    var json = {};
    json = getMainData(data, json);
    json = getChildData(json);
    var url = "fim.AppBill.Update";
    if (state == "new") {
        url = "fim.AppBill.Save";
    }
    var ret = webApi.ajax(url, json);
    if (ret) {
        if (ret.status == "0") {
            dialogBox.showMessDialog("保存成功!")
        } else {
            dialogBox.showMessDialog("保存失败:" + ret.message)
        }
    } else {
        dialogBox.showMessDialog("网络异常，请联系管理员!");
    }
    return null;
}


var isCheck = true;
var over_budger_list = new Array();

/**
 * @Description:专项对接保存时触发
 * @Param:spm数据
 * @return:
 * @Author: GongJian
 * @Date:2021年5月10日17:21:56
 */
function saveZxInfo(spm_data) {
    var date = $("#enter_date").val();
    var bb_code = $("#bb_code").val();
    var company_id = page.getCompanyId();
    var bbd_id = page.getUrlParam("bbd_id");
    var business_type_code = getBillTypeInfo(bbd_id)["business_type_code"];
    var json = {
        "subData": spm_data,
        "mainData": {
            "dj_no": bb_code,
            "contract_type": business_type_code,
            "dj_time": date,
            "company_id": company_id,
            "source_system": "bx"
        }
    };
    var ret = webApi.ajax("spm.spmNew.externalInBatchApplySave", json);
    if (ret.status == "-1") {
        return "超额";
    }
}

//保存预算数据，调用预算接口
function saveYS(valList) {
    var errMsg = "";
    var bb_code = $('#bb_code').val();
    var enter_date = $('#enter_date').val();
    var approval_date = $('#approval_date').val();
    var business_type_code = getBillTypeInfo(bbd_id)["business_type_code"];
    if (valList && valList.length > 0) {
        var json = {
            "method": "save",
            "funSystem": "bx",
            "org_id": page.getCompanyId(),
            "zx_num": bb_id,             //当前单据ID
            "zx_code": bb_code,  //当前单据code
            "cbfd_code": business_type_code,     //业务类型编码
            "cbfd_source": "",  //来源控制类型
            "applycode": "",    //预算申请单号
            "applyid": "",   //预算申请单ID
            "zx_date": enter_date,  //执行单据日期
            "cbfl_auditdate": approval_date,   //审核日期
            "cbfl_period": "",  //所属期间
            "is_apply": "",
            "valList": valList
        }
        var ret = webApi.ajax("hcbm.WBbudgetControl.WBbudgetExcute", json);
    }
}

var billTypeInfo = {"flag": "1"};

// 获取单据业务类型
function getBillTypeInfo(bbd_id) {
    if (billTypeInfo["flag"] == "1") {
        var valMap = {};
        if (page.isnotNull(bbd_id)) {
            var json = {
                "funName": "BD_ARAP_BUSINESS_TYPE",
                "funSystem": "bd",
                "valMap": {
                    "business_type_id": bbd_id
                }
            }
            var ret = webApi.ajax("system.common.queryForm", json);
            if (ret && ret.status == "0" && ret.result && ret.result.data) {
                valMap = ret.result.data;
                valMap["bx_def18"] = ret.result.data["bx_def18"];
                valMap["field_15"] = ret.result.data["field_15"];
                valMap["business_type_id"] = bbd_id
                valMap["bbd_detail_control"] = ret.result.data["bx_def13"];
                valMap["is_check_travelpartner"] = ret.result.data["bx_def8"];
                valMap["business_type_code"] = ret.result.data["business_type_code"];
                valMap["field_18"] = ret.result.data["filed_18"];
                valMap["default_collection_method"] = ret.result.data["bx_def11"];
            }
        }
        billTypeInfo = valMap;
        return valMap;
    } else {
        return billTypeInfo;
    }
}

// 将页面的数字中的逗号取消
function getPageNumber(number) {
    var newNumber = 0;
    if (page.isnotNull(number)) {
        if (typeof (number) == "string") {
            newNumber = parseFloat(number.replace(",", ""));
            newNumber = newNumber.toFixed(2);
        } else {
            newNumber = number;
        }
    }
    return newNumber;
}

//计算申请金额 = 所有费用申请明细金额
function getSaveApplyAmount() {
    var apply_amount = "0.00";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (bctdTableView) {
        var dataList = bctdTableView.getDataList();
        if (dataList.length <= 0) {
            return apply_amount;
        }
        for (var i = 0; i < dataList.length; i++) {
            if (page.isnotNull(dataList[i].amount)) {
                apply_amount = parseFloat(apply_amount) + parseFloat(dataList[i].amount);
            }
        }
    }
    if (page.isnotNull(apply_amount)) {
        apply_amount = parseFloat(apply_amount).toFixed(2);
    }
    return apply_amount;
}

//计算预算申请金额 = 所有本次申请金额
function getBrcsdAmount() {
    var brcsd_amount = "0.00";
    var brcsdTableView = Form.getAppTablView("costShareDetailList_appTable");
    if (brcsdTableView) {
        var dataList = brcsdTableView.getDataList();
        if (dataList.length <= 0) {
            return brcsd_amount;
        }
        for (var i = 0; i < dataList.length; i++) {
            if (page.isnotNull(dataList[i].brcsd_amount)) {
                brcsd_amount = parseFloat(brcsd_amount) + parseFloat(dataList[i].brcsd_amount);
            }
        }
    }
    if (page.isnotNull(brcsd_amount)) {
        brcsd_amount = parseFloat(brcsd_amount).toFixed(2);
    }
    return brcsd_amount;
}

//计算专项申请金额 = 所有本次申请金额
function getZXBrcsdAmount() {
    var brcsd_amount = "0.00";
    var brcsdTableView = Form.getAppTablView("costShareDetailListZX_appTable");
    if (brcsdTableView) {
        var dataList = brcsdTableView.getDataList();
        if (dataList.length <= 0) {
            return brcsd_amount;
        }
        for (var i = 0; i < dataList.length; i++) {
            if (page.isnotNull(dataList[i].brcsd_amount)) {
                brcsd_amount = parseFloat(brcsd_amount) + parseFloat(dataList[i].amount);
            }
        }
    }
    if (page.isnotNull(brcsd_amount)) {
        brcsd_amount = parseFloat(brcsd_amount).toFixed(2);
    }
    return brcsd_amount;
}

function doSavedAction(data, state) {
    isCheck = true;
    if (state == "update") {
        linkRefresh(data);
    }
}

//刷新页面
function linkRefresh(data) {
    if (data.status == 'BC') {
        $($(".btn_submit")[1]).removeAttr("disabled");
        $($(".btn_submit")[1]).removeAttr("style");
    }
}

//申请人选中后的回调方法
function caUserConfirm(e) {
    console.log("点击申请人，选择了：" + JSON.stringify(e));
}


function orgIdConfirm(e) {
    console.log("点击组织，选择了：" + JSON.stringify(e));
    $("#org_id").attr("readonly", "readonly");
    $("#position").val(e.position)
    // var dataList = [];
    // ret = orgs;
    // for (var i = 0; i < ret.length; i++) {
    //     dataList.push({
    //         "value": ret[i].value,
    //         "text": ret[i].text,
    //         "position": ret[i].position
    //     })
    //     if (old_org_id) {
    //         if (ret[i].value == old_org_id) {
    //             $("#org_id").val(ret[i].text);
    //             $("#org_id").attr("org_id", old_org_id);
    //             $("#position").val(ret[i].position);
    //         } else {
    //             json = {
    //                 "funName": "queryOrgListForSelect",
    //                 "funSystem": "sf",
    //                 "valMap": {
    //                     "org_list": old_org_id
    //                 }
    //             }
    //             var orgData = webApi.ajax("common.queryList", json).result.data;
    //             $("#org_id").val(orgData[0].oname);
    //             $("#org_id").attr("org_id", orgData[0].oid);
    //             $("#position").val(ret[i].position);
    //         }
    //     } else {
    //         if (ret[i].value == emp_map[$("#user_id").val() + "_jobs_in_dept"]) {
    //             $("#org_id").val(ret[i].text);
    //             $("#org_id").attr("org_id", ret[i].value);
    //             $("#position").val(ret[i].position);
    //         }
    //     }
    // }
    // orgSelectCtrl = new mui.PopPicker({
    //     layer: 1
    // });
    // orgSelectCtrl.setData(dataList);
    // var ctrl = document.getElementById("org_id");
    // ctrl.addEventListener("tap", function (event) {
    //     orgSelectCtrl.show(function (items) {
    //         $("#org_id").val(items[0].text);
    //         $("#org_id").attr("org_id", items[0].value);
    //         $("#position").val(items[0].position)
    //     });
    // }, false);
}

// 预保存
function perSaveForm(bb_id, flag) {
    if (page.isnotNull(zc_bb_id)) {
        bb_id = zc_bb_id;
        flag = "add";
    }
    var isPreSave = false;
    var data = {};
    data.bb_id = bb_id;
    data.user_name = $("#ca_user").text();
    data.user_id = getUSERID();
    data.org_id = getORGID();// 所在科室
    data.company_id = getCOMPANYID();// 单位默认第一
    data.bbd_id = page.getUrlParam("bbd_id");// 单据类型
    data.reason = $("#reason").val();//事由
    data.travel_date = $("#travel_date").val();
    data.return_date = $("#return_date").val();
    data.travel_days = $("#travel_days").val();
    data.metting_count = $("#metting_count").val();
    data.travel_period = $("#travel_period").val();
    data.apply_amount = getSaveApplyAmount();
    if (!data.apply_amount) {
        data.apply_amount = "0.00";
    }
    var status = $("#status").val();
    if (page.isnotNull(status)) {
        data.status = status;
    } else {
        data.status = "ZC";// 单据状态暂存
    }
    data.area = $("#area").attr("data-areaid");
    var costor = "";
    if ($("input[name='costor']").eq(0).attr("type") == "checkbox") {
        if ($("input[name='costor']").eq(0).is(":checked")) {
            costor = "01";
        }
        if ($("input[name='costor']").eq(1).is(":checked")) {
            if (costor) {
                costor = costor + ",02"
            } else {
                costor = "02";
            }
        }
        if ($("input[name='costor']").eq(2).is(":checked")) {
            if (costor) {
                costor = costor + ",03"
            } else {
                costor = "03";
            }
        }
    } else {
        costor = $("#costor").val();
    }
    data.costor = costor;
    data.receive_user = getUSERID();//收款员工
    data.rate = "1";
    data.currency = "CYN"
    data.pc_form_code = page.getUrlParam("formCode");
//添加费用对象名称
    var costorName = "";
    if (data.costor) {
        if (data.costor.indexOf("01") > -1) {
            costorName += "单位,"
        }
        if (data.costor.indexOf("02") > -1) {
            costorName += "个人,"
        }
        if (data.costor.indexOf("03") > -1) {
            costorName += "院外人员,"
        }
        data.costor_name = costorName.substr(0, costorName.length - 1);
    }
    //员工收款银行账户
    var json = {
        "funName": "querybxEmpInfo",
        "funSystem": "bd",
        "valMap": {
            "bhe_id": getUSERID()
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret.status == "0" && ret.result.data.length > 0) {
        data.receive_user_bankinfo = ret.result.data[0].jobs_wagesnum;
        data.user_mobile = ret.result.data[0].persion_moddle_num;
    }
    //支付方式
    var json = {
        "funName": "BD_ARAP_BUSINESS_TYPE",
        "funSystem": "bd",
        "valMap": {
            "business_type_id": bbd_id
        }
    }
    var ret = webApi.ajax("system.common.queryForm", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data) {
        data.pay_type = ret.result.data["bx_def11"];
    }

    var yearCount = 0;
    var enter_date = format.getDate().substring(0, 4);
    var json = {
        "funName": "queryBusinessCountYear",
        "valMap": {
            "bbd_id": bbd_id,
            "delete_flag": "0",
            "status": "YSP",
            "enter_date": enter_date + "%"
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
        data.extend3 = parseInt(ret.result.data[0]["count"]);//年度出差次数
    }
    if ($("#travel_tools").length == 1) {
        data.travel_tools = $("#travel_tools").val();//交通工具
    }
    if ($("#organizer").length == 1) {
        if ($("#organizer").val()) {
            data.organizer = $("#organizer").val()//主办单位
        }
    }
    if ($("#travel_type").length == 1) {
        if ($("#travel_type").val()) {
            data.travel_type = $("#travel_type").val()//外出类型
        }
    }
    if ($("#recept_count").length == 1) {
        if ($("#recept_count").val()) {
            data.recept_count = $("#recept_count").val();//接待人数
        }
    }
    if ($("#accompany_count").length == 1) {
        if ($("#accompany_count").val()) {
            data.accompany_count = $("#accompany_count").val();//陪同人数
        }
    }
    if ($("#metting_type").length == 1) {
        if ($("#metting_type").val()) {
            data.metting_type = $("#metting_type").val();//会议类型
        }
    }
    if ($("#train_type").length == 1) {
        if ($("#train_type").val()) {
            data.train_type = $("#train_type").val();//培训类型
        }
    }
    //预置字段
    if ($("#extend1").length == 1) {
        if ($("#extend1").val()) {
            data.extend1 = $("#extend1").val();
        }
    }
    if ($("#extend2").length == 1) {
        if ($("#extend2").val()) {
            data.extend2 = $("#extend2").val();
        }
    }
    if ($("#extend3").length == 1) {
        if ($("#extend3").val()) {
            data.extend3 = $("#extend3").val();
        }
    }
    if ($("#extend4").length == 1) {
        if ($("#extend4").val()) {
            data.extend4 = $("#extend4").val();
        }
    }
    if ($("#extend5").length == 1) {
        if ($("#extend5").val()) {
            data.extend5 = $("#extend5").val();
        }
    }
    if ($("#extend6").length == 1) {
        if ($("#extend6").val()) {
            data.extend6 = $("#extend6").val();
        }
    }
    if ($("#extend7").length == 1) {
        if ($("#extend7").val()) {
            data.extend7 = $("#extend7").val();
        }
    }
    if ($("#extend8").length == 1) {
        if ($("#extend8").val()) {
            data.extend8 = $("#extend8").val();
        }
    }
    if ($("#extend9").length == 1) {
        if ($("#extend9").val()) {
            data.extend9 = $("#extend9").val();
        }
    }
    if ($("#extend10").length == 1) {
        if ($("#extend10").val()) {
            data.extend10 = $("#extend10").val();
        }
    }
    if (flag == "add") {
        data.app_form_code = page.getUrlParam("formCode");
        data.delete_flag = "0";
        data.bx_bill_link = "0";
        data.entor = "{userid}";
        data.enter_date = "{strdatetime}";
        data.oattribute = queryOattribute(empInfo["jobs_in_dept"]);//核算属性
        var form_code = page.getUrlParam("formCode");
        if (page.isnotNull(form_code)) {
            form_code = form_code.substring(0, form_code.length - 4);
        } else {
            form_code = "";
        }
        data.bb_code = page.getSerialNumber("BX_BILL_CODE", {});
        data.bb_name = "申请单据" + format.dateFormat(new Date(), "yyyyMMddHHmmss");
    }
    var valList = new Array();
    valList.push(data);
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valList": valList,
        "funDbType": flag
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret && ret.status == "0") {
        $("#bb_id").val(bb_id);
        isPreSave = true;
        var items = urlStack.getItems();
        items[items.length - 1][urlStack.getCurPageIndex()] = items[items.length - 1][urlStack.getCurPageIndex()] + "&bb_id=" + bb_id;
        urlStack.setItems(items);
    } else {
        dialogBox.alert("单据异常:" + ret.message);
    }

    var data = Form.getAppFormData();
    if (!page.isnotNull(data)) return isPreSave;
    var ysTableView = Form.getAppTablView("ywNewShareDetailList");
    if (ysTableView && ysTableView.getDataList().length > 0) {
        var checkResult = checkRefundBillYS(data);
        if (!checkResult) return;
    }
    return isPreSave;
}

// 页面控件控制
function controlCtrl() {
    // 费用明细
    var cxCtrl = $("#costDetailList");
    if (cxCtrl && cxCtrl.length <= 0) {
        var titleHTMLCX = "";
        titleHTMLCX += "<p class='detailedTtitle' id='title_cd'>费用明细</p>";
        titleHTMLCX += "<p class='detailedBtn' id='btn_cd' onclick='btnFY()'>添加明细</p>";
        $("#costDetailTitle").addClass("mui-input-row");
        $("#costDetailTitle").append(titleHTMLCX);
    }
    //同行人
    var txCtrl = $("#appBxTravelPartnerList");
    if (txCtrl && txCtrl.length > 0) {
        var titleHTMLTX = ""
        titleHTMLTX += "<p class='detailedTtitle' id='title_tx'>同行人</p>";
        if (bb_id) {
            if (parseInt(FormData.partnerCount) > 0) {
                titleHTMLTX += "<p class='detailedBtn' id='btn_tx' onclick='btnTX()'>" + FormData.partnerCount + "</p>";
            } else {
                titleHTMLTX += "<p class='detailedBtn' id='btn_tx' onclick='btnTX()'>0</p>";
            }
        } else {
            titleHTMLTX += "<p class='detailedBtn' id='btn_cd' onclick='btnTX()'>0</p>";
        }
        $("#appBxTravelPartnerList").append(titleHTMLTX);
    }
    //预算明细
    var bbd_cost_type = getBbdCostType(bbd_id);
    if (bbd_cost_type == "NO") {
        // 预算
        $("#costShareDetailTitle_container").hide();
        $("#costShareDetailList_container").hide();
        $("#costShareDetailTitle_container").parent(".new_form_modularBox").hide();
        // 专项
        $("#costShareDetailTitleZX_container").hide();
        $("#costShareDetailListZX_container").hide();
        $("#costShareDetailTitleZX_container").parent(".new_form_modularBox").hide();
        // 新预算
        $("#ysNewListTitle_container").hide();
        $("#ywNewShareDetailList_container").hide();
        $("#ysNewListTitle_container").parent(".new_form_modularBox").hide();
    } else if (bbd_cost_type == "CBMS") {
        $("#costShareDetailTitleZX_container").hide();
        $("#costShareDetailListZX_container").hide();
        $("#costShareDetailTitleZX_container").parent(".new_form_modularBox").hide();

        $("#ysNewListTitle_container").hide();
        $("#ywNewShareDetailList_container").hide();
        $("#ysNewListTitle_container").parent(".new_form_modularBox").hide();
        // 预算明细
        var titleHTMLYS = "";
        var AddysCtrl = $("#costShareDetailTitle");
        if (AddysCtrl && AddysCtrl.length > 0) {
            titleHTMLYS += "<p class='detailedTtitle' id='title_ys'>预算匹配</p>";
            titleHTMLYS += "<p class='detailedBtn' id='btn_ys' onclick='btnAddYs()'>添加预算</p>";
            $("#costShareDetailTitle").addClass("mui-input-row");
            $("#costShareDetailTitle").append(titleHTMLYS);
        }
    } else if (bbd_cost_type == "SPM") {
        $("#costShareDetailTitle_container").hide();
        $("#costShareDetailList_container").hide();
        $("#costShareDetailTitle_container").parent(".new_form_modularBox").hide();

        $("#ysNewListTitle_container").hide();
        $("#ywNewShareDetailList_container").hide();
        $("#ysNewListTitle_container").parent(".new_form_modularBox").hide();
        // 专项预算明细
        var titleHTMLYSZX = "";
        var AddysCtrlZX = $("#costShareDetailTitleZX");
        if (AddysCtrlZX && AddysCtrlZX.length > 0) {
            titleHTMLYSZX += "<p class='detailedTtitle' id='title_yszx'>专项预算明细</p>";
            titleHTMLYSZX += "<p class='detailedBtn' id='btn_yszx' onclick='btnAddYsZX()'>选择项目</p>";
            $("#costShareDetailTitleZX").addClass("mui-input-row");
            $("#costShareDetailTitleZX").append(titleHTMLYSZX);
        }
    } else {
        $("#costShareDetailTitle_container").hide();
        $("#costShareDetailList_container").hide();
        $("#costShareDetailTitle_container").parent(".new_form_modularBox").hide();
        $("#costShareDetailTitleZX_container").hide();
        $("#costShareDetailListZX_container").hide();
        $("#costShareDetailTitleZX_container").parent(".new_form_modularBox").hide();
        // 新预算明细
        var ysNewCtrl = $("#title_ysNew");
        if (ysNewCtrl || ysNewCtrl.length <= 0) {
            var ysNewTitleHTML = "<p class='detailedTtitle' id='title_ysNew'>预算明细</p>";
            ysNewTitleHTML += "<p class='detailedBtn' id='btn_xmys' onclick='btnAddYsNew()'>分配预算</p>";
            $("#ysNewListTitle").addClass("mui-input-row");
            $("#ysNewListTitle").append(ysNewTitleHTML);
        }
    }
}

// 分配预算（新预算）
function btnAddYsNew() {
    var bb_id = $("#bb_id").val();
    var bbd_id = getBBDID();
    var form_code = page.getUrlParam("formCode");
    var flag = "add";
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var bdTableView = Form.getAppTablView("costDetailList_appTable");
    var dataList = bdTableView.getDataList();
    var bbd_detail_control = getBillTypeInfo(bbd_id)["bx_def13"];
    if (bbd_detail_control && bbd_detail_control == "1" && dataList && dataList.length == 0) {
        dialogBox.alert("请先填写费用明细!");
        return false;
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    sessionStorage.removeItem("detailList");
    var _userId = page.getDefaultParam("userid"); // 当前登录人
    var _bxDef19 = getBillTypeInfo(bbd_id)["bx_def19"]; // 预算来源
    var _companyId = page.getCompanyId();
    var _businessTypeCode = getBillTypeInfo(bbd_id)["business_type_code"]; // 业务类型编码
    var bdTableView = Form.getAppTablView("costDetailList_appTable");
    if (bdTableView) {
        var dataList = bdTableView.getDataList();
        sessionStorage.setItem("detailList", JSON.stringify(dataList));
    }
    url = "/html/Common/List.html?ListCode=BxYsDataList&form_type=apply&bb_id=" + bb_id + "&user_id=" + _userId + "&form_code=" + form_code + "&bus_type_id=" + bbd_id + "&ys_type=" + _bxDef19 + "&company_id=" + _companyId + "&bus_type_code=" + _businessTypeCode;
    page.openWindow(url);
}

//添加预算
function btnAddYs() {
    var bb_id = $("#bb_id").val();
    var form_code = page.getUrlParam("formCode");
    var flag = "add";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    //有且只有一条预算：点击‘添加预算’，可以自动带出预算号
    var data = {};
    var yscountLists = defaultAddYS(bb_id, bbd_id, data);
    if (yscountLists && yscountLists.length == 1) {
        window.location.reload();
    }
    //有0条预算：点击‘添加预算’，提示无可用预算号
    if (yscountLists && yscountLists.length == 0) {
        // dialogBox.showMessDialog("无可用预算号！");
    }
    //一条上预算，点击‘添加预算’跳转预算列表
    if (yscountLists && yscountLists.length > 1) {
        var emp_id = $("#user_id").val();
        var user_id = getUserId(emp_id);
        var apply_amount = getSaveApplyAmount();
        url = "/html/Common/List.html?ListCode=costApplyYSDetailList&bb_id=" + bb_id + "&form_code=" + form_code + "&bbd_id=" + bbd_id + "&user_id=" + user_id + "&apply_amount=" + apply_amount;
        page.openWindow(url);
    }
}

//添加预算
function btnAddYsZX() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    var bctdTableView = Form.getAppTablView("costDetailList_appTable");
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    var apply_amount = getSaveApplyAmount();
    var formCode = page.getUrlParam("formCode");
    url = "/html/common/Form.html?formCode=zxCostShareDetailForm&bb_id=" + bb_id + "&apply_amount=" + apply_amount + "&bbd_id=" + bbd_id + "&form_code=" + formCode;
    page.openWindow(url);
}

function defaultAddYS(bb_id, bbd_id) {
    var dicList = new Array(); //预算号信息
    var bdTableView = Form.getAppTablView("costDetailList_appTable");
    if (bdTableView) {
        var dataList = bdTableView.getDataList();
        if (dataList && dataList.length > 0) {//必须添加费用明细后才能添加预算
            var emp_id = $("#user_id").val();
            var user_id = getUserId(emp_id);
            var json = {
                "type": "BXBillGetYSH",
                "valMap": {
                    "bb_id": bb_id,
                    "bbd_id": bbd_id,
                    "user_id": user_id
                }
            }
            var ret = webApi.ajax("fim.bx.linkYSHUrl", json);
            if (ret && ret.status == "0" && ret.data) {
                var result = {};
                result["data"] = ret.data;
                var head = {};
                head["total"] = ret.data.length;
                result["head"] = head;
                ret["result"] = result;
            }
            if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
                dicList = ret.result.data;
            }
            if (dicList && dicList.length == 1) {
                //若对应的只有一个预算号默认显示，就不用跳转至预算列表，则暂存至该报销单
                var row = dicList[0];
                var newdicList = new Array();
                var yApplyAmount = isNanF(row.yApplyAmount);
                for (var i = 0; i < dicList.length; i++) {
                    //var data = {};
                    data["bcsd_id"] = page.getuuid();// ID
                    data["bb_id"] = bb_id;// 报销单据ID
                    data["bbd_cost_type"] = "CBMS";// 分摊类型 当前为
                    data["budget_id"] = dicList[i].budget_id;// 预算号
                    data["history_id"] = dicList[i].history_id;//历史主键ID
                    data["bproject_id"] = dicList[i].bproject_id;// 预算指标ID
                    data["bproject_name"] = dicList[i].bproject_name;// 预算指标名称
                    if (!page.isnotNull(dicList[i].bproject_name)) {
                        data["bproject_name"] = dicList[i].bname;
                    }
                    data["bdept_man_id"] = dicList[i].bdept_man_id;// 承担科室 预算科室
                    data["bdept_man_name"] = dicList[i].bdept_man_name;// 承担科室名称
                    data["mdept_id"] = dicList[i].mdept_id;// 管理科室 归口科室
                    data["mdept_name"] = dicList[i].mdept_name;// 管理科室名称
                    data["budget_number"] = dicList[i].budget_number//预算总额
                    data["implement_number"] = dicList[i].act_number//执行额
                    data["bname"] = dicList[i].bname; //指标名称
                    data["finalversion_id"] = dicList[i].finalversion_id; //预算号主键
                    data["ctrl_num"] = dicList[i].ctrl_num;  //项目已占有额
                    data["left_num"] = dicList[i].left_num;  //剩余可使用预算额
                    data["bdept_status"] = "1"//是否可用
                    var yNum = dicList[i].adjust_budget_num;
                    if (!page.isnotNull(yNum)) {
                        yNum = dicList[i].perfrom_num;
                    }
                    data["bproject_balance"] = isNanF(yNum) - isNanF(dicList[i].act_number);// 预算余额 = 预算数 - 已执行数量
                    if (yApplyAmount >= 0) {
                        data["is_over_budget"] = "0";// 是否超预算
                    } else {
                        data["is_over_budget"] = "1";// 是否超预算
                        yApplyAmount = 0;
                    }
                    if (dicList.length == 1) {
                        data["brcsd_amount"] = yApplyAmount;
                    } else {
                        data["brcsd_amount"] = "0.00";
                    }
                    data["source"] = "1"; //来源 1 自制
                    newdicList.push(data);
                }

                var json = {
                    "funName": "BX_COST_SHARE_DETAIL",
                    "funSystem": "bx",
                    "valList": newdicList,
                    "funDbType": "add"
                }
                var ret = webApi.ajax("system.common.submitForm", json);
                if (ret && ret.status == "0") {
                    dialogBox.showMessDialog("添加预算成功!");

                } else {
                    dialogBox.alert("添加预算失败:" + ret.message);
                }
            }

        } else {
            dialogBox.alert("请先填写费用明细!");
        }
    }
    return dicList;
}

//同行人
function btnTX() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    if (!bbd_id) {
        dialogBox.alert("单据类型不存在！");
        return;
    }
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    } else {
        page.openWindow("/html/common/Form.html?formCode=appTravelPartnerForm&bb_id=" + bb_id + "&bbd_id=" + bbd_id);
    }
}

//城市控件
function initCityCtrl() {
    var area = $("#area");
    if (area && area.length > 0) {
        format.cityPicker("area", null);
    }
}

//费用明细
function btnFY() {
    var bb_id = $("#bb_id").val();
    var flag = "add";
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    var isPreSave = perSaveForm(bb_id, flag);
    if (!isPreSave) {
        return;
    }
    cadCtrl.show(function (items) {
        var bct_id = items[0].value;
        var bproject_id = items[0].bproject_id;
        if (page.isnotNull(bct_id)) {
            var train_type = $("#train_type").val();
            var metting_type = $("#metting_type").val();
            var area_id = $("#area").attr("data-areaid");
            var bcs_amount = "0.00";
            if (!train_type) {
                train_type = null;
            }
            if (!metting_type) {
                metting_type = null;
            }
            if (!area_id) {
                area_id = null;
            }
            page.openWindow("/html/common/Form.html?formCode=AppCostApplyDetailForm&bb_id=" + bb_id + "&bct_id=" + bct_id + "&cost_eval=" + bcs_amount + "&bproject_id=" + bproject_id);
        } else {
            dialogBox.alert("加载失败!");
        }
    });
}

var cadCtrl;

function createButton() {
    var valMap = {};
    var childList = new Array();
    var param_value = page.isnotNull(FormData.paramPropertyValue) ? FormData.paramPropertyValue : "";
    if (!param_value || param_value == "0") {
        company_id = "-";
    }
    var dataList = page.isnotNull(FormData["costDetail"]) ? FormData["costDetail"] : [];
    if (dataList && dataList.length > 0) {
        for (var j = 0; j < dataList.length; j++) {
            var childMap = {};
            childMap["value"] = dataList[j].value;
            childMap["text"] = dataList[j].bct_name;
            childMap["bproject_id"] = dataList[j].bproject_id;
            childList.push(childMap);
        }
    }
    valMap["children"] = childList;
    cadCtrl = new mui.PopPicker({
        layer: 1
    });
    cadCtrl.setData(childList);
}

//获取申请人对应的用户id,获取不到则取当前登录用户的id
function getUserId(emp_id) {
    var fileJson = {
        "funName": "queryUserIdByEmpId",
        "funType": "C",
        "valMap": {
            "user_emp_id": emp_id
        },
    };
    var resultData = webApi.ajax("system.common.queryList", fileJson);
    var user_id = page.isnotNull(resultData.result.data[0].user_id) ? resultData.result.data[0].user_id : "{userid}";
    return user_id;
}

//设置日期控件
function initDateCtrl() {
    if (!page.isnotNull($("#travel_date").val())) {
        $("#travel_date").text("请选择");
    }
    if (!page.isnotNull($("#return_date").val())) {
        $("#return_date").text("请选择");
    }
    var start_date = $("#travel_date");
    if (start_date && start_date.length > 0) {
        format.dtPicker("travel_date", "date", calculateDays);
    }
    var end_date = $("#return_date");
    if (end_date && end_date.length > 0) {
        format.dtPicker("return_date", "date", calculateDays);
    }
}

//计算日期
function calculateDays() {
    var startDate = $("#travel_date").val();
    var endDate = $("#return_date").val();
    if (dateCalculate.length == 0) {
        var bbd_id = getBBDID();
        var json = {
            "funName": "queryDateCalcuByBbd",
            "funSystem": "bx",
            "valMap": {
                "bbd_id": bbd_id
            }
        }
        var ret = webApi.ajax("system.common.queryList", json);
        if (ret && ret.status == "0" && ret.result && ret.result.data.length > 0) {
            dateCalculate.push(ret.result.data[0]);
        } else {
            dateCalculate.push({"null": "true"});
        }
    } else if (!page.isnotNull(dateCalculate[0].null)) {
        if (page.isnotNull(startDate) && page.isnotNull(endDate)) {
            var startDateTime = new Date(startDate);
            var endDateTime = new Date(endDate);
            var flag = parseInt((parseInt(endDateTime.getTime()) - parseInt(startDateTime.getTime())) / (24 * 60 * 60 * 1000)) + 1;
            if (flag < 1) {
                dialogBox.showMessDialog("结束日期必须大于等于开始日期");
                $("#travel_days").val("");
                $("#travel_date").val("");
                $("#return_date").val("");
                return;
            }
            var days = 0;
            if (dateCalculate[0].bdc_start_date == "1") days = days + 1;
            if (dateCalculate[0].bdc_end_date == "1") days = days + 1;
            if (dateCalculate[0].bdc_difference == "1") days = days + flag;
            if (!page.isnotNull(dateCalculate[0].bdc_change_days)) dateCalculate[0].bdc_change_days = "0";
            if (!isNaN(parseInt(dateCalculate[0].bdc_change_days))) days = days + parseInt(dateCalculate[0].bdc_change_days);
            if (page.isnotNull(dateCalculate[0].bdc_min_days) && days < parseFloat(dateCalculate[0].bdc_min_days)) {
                days = parseFloat(dateCalculate[0].bdc_min_days);
            } else if (page.isnotNull(dateCalculate[0].bdc_max_days) && days > parseFloat(dateCalculate[0].bdc_max_days)) {
                days = parseFloat(dateCalculate[0].bdc_max_days);
            }
            $("#travel_days").val(parseFloat(days).toFixed(1));
            // 出差期限
            if (days < 91) {
                $("#travel_period").val("LessThanThreeMonth");
            } else if (days < 181) {
                $("#travel_period").val("ThreeMonthToHalfYear");
            } else if (days < 366) {
                $("#travel_period").val("HalfToYear");
            } else if (days > 365) {
                $("#travel_period").val("OneYearOrMore");
            }
        }
    } else {
        if (page.isnotNull(startDate) && page.isnotNull(endDate)) {
            var startDateTime = new Date(startDate);
            var endDateTime = new Date(endDate);
            var days = parseInt((parseInt(endDateTime.getTime()) - parseInt(startDateTime.getTime())) / (24 * 60 * 60 * 1000));
            if (days < 0) {
                dialogBox.alert("结束日期不能小于开始日期");
                $("#travel_days").val("");
                $("#travel_date").val("");
                $("#return_date").val("");
                return;
            } else {
                // 出差天数
                var days = parseInt(days) + 1;
                $("#travel_days").val(days);
                // 出差期限
                if (days < 91) {
                    $("#travel_period").val("LessThanThreeMonth");
                } else if (days < 181) {
                    $("#travel_period").val("ThreeMonthToHalfYear");
                } else if (days < 366) {
                    $("#travel_period").val("HalfToYear");
                } else if (days > 365) {
                    $("#travel_period").val("OneYearOrMore");
                }
            }
            var daysCtrl = $("#travel_days");
            if (daysCtrl && daysCtrl.length > 0) {
                daysCtrl.val(days);
            }
        }
    }
}

//快速引用费用明细
function addDetail() {
    var bb_id = page.getUrlParam("bb_id");
    var flag = "add";
    if (!page.isnotNull(bb_id)) {
        bb_id = page.getuuid();
    } else {
        flag = "update";
    }
    if (flag == "add") {
        var isPreSave = perSaveForm(bb_id, flag);
        if (!isPreSave) {
            return;
        }
        var param_value = page.isnotNull(FormData.paramPropertyValue) ? FormData.paramPropertyValue : "";
        if (!param_value || param_value == "0") {
            company_id = "-";
        }
        if (bbd_id) {
            //查询快速引用的费用类型
            var jsone = {
                "funName": "queryReference",
                "funSystem": "bx",
                "valMap": {
                    "bbd_id": bbd_id,
                    "company_id": company_id
                }
            }
            var ret1 = webApi.ajax("system.common.queryList", jsone);
            if (ret1.status == "0" && ret1.result.data.length > 0) {
                var dataList = ret1.result.data
                var valList = new Array();
                for (var i = 0; i < dataList.length; i++) {
                    valList.push({
                        "cad_id": page.getuuid(),
                        "bct_id": dataList[i].bct_id,
                        "bb_id": bb_id,
                        "bproject_id": dataList[i].bproject_id,
                        "amount": "0.00"
                    })
                }
                var json = {
                    "funName": "BX_COST_APPLY_DETAIL",
                    "funSystem": "bx",
                    "valList": valList
                }
                var ret = webApi.ajax("system.common.submitForm", json);
                if (ret.status != "0") {
                    dialogBox.showMessDialog("快速引用费用明细失败");
                }
                var formCode = page.getUrlParam("formCode");
                var url = "/html/common/Form.html?formCode=" + formCode + "&bbd_id=" + bbd_id + "&bb_id=" + bb_id;
                urlStack.splice();
                page.openWindow(url)
            }
        }
    }
}

// 获取ORG_ID
function getORGID() {
    var org_id = $("#org_id").attr("org_id")
    if (!page.isnotNull(org_id)) {
        org_id = page.getUrlParam("org_id");
    }
    return org_id;
}

// 获取承担人
function getUSERID() {
    var user_id = $("#user_id").val();
    if (!page.isnotNull(user_id)) {
        user_id = "";
    }
    if (!page.isnotNull(user_id.trim())) {
        user_id = empInfo["bhe_id"];
    }
    return user_id;
}

// 获取当前默认单位
function getCOMPANYID() {
    var company_id = $("#company_id").val();
    if (!page.isnotNull(company_id)) {
        company_id = page.getCompanyId();
    }
    return company_id;
}

function groupBy(array, name) {
    var map = {};
    for (var i = 0; i < array.length; i++) {
        var n = array[i][name];
        if (!map[n]) {
            map[n] = [];
        }
        map[n].push(array[i])
    }
    return map;
}

//数字格式化
function isNanF(value) {
    if (page.isnotNull(value)) {
        if (!isNaN(value)) {
            value = parseFloat(value);
        } else {
            value = 0;
        }
    } else {
        value = 0;
    }
    return value;
}

// 查询当前人员对应的科室的核算属性
function queryOattribute(org_id) {
    if (page.isnotNull(org_id)) {
        var json = {
            "funName": "queryOattributeByOid",
            "valMap": {
                "oid": org_id
            }
        }
        var ret = webApi.ajax("system.common.queryList", json);
        if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
            var oattribute = ret.result.data[0].oattribute;
            if (page.isnotNull(oattribute) && oattribute != "-") {
                return oattribute;
            }
        }
    }
}

//提交及业务处理
function statrFlowForForm_new() {
    var bill_type_info = getBillTypeInfo(bbd_id);
    var mustUpLoadFile = bill_type_info.field_18;
    if (mustUpLoadFile) {
        if ($("#extend20_upload_ul > li").length == 0) {
            dialogBox.alert("当前单据必须提交附件！");
            return;
        }
    }
    startFlowForForm();
}

// 流程提交后触发
function doStartflowData(data) {
    var bb_id = data.formId;
    var bbd_cost_type = '';
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": bb_id
        }
    }
    var ret = webApi.ajax("system.common.queryForm", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data) {
        bbd_cost_type = getBbdCostType(ret.result.data["bbd_id"])
    }
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": bb_id,
            "status": "YTJ"
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret) {
        if (bbd_cost_type == 'SPM') {
            zxSubmit();
        }
        if (ret.status != "0") {
            dialogBox.showMessDialog("提交成功！");
        }
    } else {
        dialogBox.alert(ret.message);
    }
}

/**
 * @Description:专项对接审批通过时触发
 * @Param:单据编码
 * @return:
 * @Author: GongJian
 * @Date:2021年5月10日
 */
function zxFlowend(bb_code) {
    var json = {"dj_no": bb_code};
    var ret = webApi.ajax("spm.spmNew.externalInBatchSmitPass", json);
}

/**
 * @Description:专项对接提交时触发
 * @Param:单据编码
 * @return:
 * @Author: GongJian
 * @Date:2021年5月10日16:00:05
 */
function zxSubmit() {
    var dj_no = $("#bb_code").val();
    var json = {"dj_no": dj_no};
    var ret = webApi.ajax("spm.spmNew.externalInBatchSmit", json);
}

// 流程提交后二次开发事件 f 1表示处理第一个节点，2处理第二个节点....
function doFlowSubmit(mainId, flowCode, flowId, f) {
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": mainId,
            "status": "SPZ",
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
}

// 二次开发第一次提交
function flowFristSub(sfis_formid) {
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": sfis_formid,
            "status": "SPZ",
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
}

// 流程废除
function doAbolishFlow(sfis_formid, sfn_code, sfi_id) {
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": sfis_formid,
            "status": "BC",
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret && ret.status == "0") {
        dialogBox.showMessDialog("取消审批成功！");
        setTimeout(function () {
            window.location.reload();
        }, 500);
    } else {
        dialogBox.alert(ret.message);
    }
}

// 流程终止
function doAbolishFlowForm(bb_id) {
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": bb_id,
            "status": "YBH",
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret && ret.status == "0") {
        dialogBox.showMessDialog("取消审批成功！");
        setTimeout(function () {
            window.location.reload();
        }, 500);
    } else {
        dialogBox.alert(ret.message);
    }
}

function dobackFlowSubmit(sfis_formid, sfi_id, sfn_code, index) {
    if (index == "1") {
        var json = {
            "funName": "BX_BILL",
            "funSystem": "bx",
            "valMap": {
                "bb_id": sfis_formid,
                "status": "BC",
            }
        }
        var ret = webApi.ajax("system.common.submitForm", json);
        if (ret && ret.status == "0") {
            dialogBox.showMessDialog("取回成功！");
            var json2 = {
                "funName": "BX_BILL",
                "funSystem": "bx",
                "valMap": {
                    "bb_id": sfis_formid,
                }
            }
            var ret2 = webApi.ajax("system.common.queryForm", json2);
            if (ret2 && ret2.status == "0" && ret2.result && ret2.result.data) {
                var bb_code = ret2.result.data['bb_code'];
                zxBack(bb_code);
            }
            setTimeout(function () {
                window.location.reload();
            }, 500);
        } else {
            dialogBox.alert(ret.message);
        }
    }
}

/**
 * @Description:专项对接单据取回时触发
 * @Param:单据编码
 * @return:
 * @Author: GongJian
 * @Date:2021年5月8日10:58:14
 */
function zxBack(bb_id) {
    var json = {"dj_no": bb_id};
    var ret = webApi.ajax("spm.spmNew.externalInBatchBack", json);
}

//取回后二次开发
function doQHFlowSubmit(mainId, flowCode, flowId, f) {
    if (f == "1") {
        var json = {
            "funName": "BX_BILL",
            "funSystem": "bx",
            "valMap": {
                "bb_id": mainId,
                "status": "BC",
            }
        }
        var ret = webApi.ajax("system.common.submitForm", json);
        if (ret && ret.status == "0") {
            dialogBox.showMessDialog("取回成功！");
            var json2 = {
                "funName": "BX_BILL",
                "funSystem": "bx",
                "valMap": {
                    "bra_id": mainId,
                }
            }
            var ret2 = webApi.ajax("system.common.queryForm", json2);
            if (ret2 && ret2.status == "0" && ret2.result && ret2.result.data) {
                var bb_code = ret2.result.data['bb_code'];
                zxBack(bb_code);
            }
            setTimeout(function () {
                window.location.reload();
            }, 500);
        } else {
            dialogBox.alert(ret.message);
        }
    }
}

//二次开发 流程结束调用
function flowEnd(sfis_mainid) {
    var bb_code = '';
    var bbd_cost_type = '';
    var bxysData = {};
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": sfis_mainid
        }
    }
    var ret = webApi.ajax("system.common.queryForm", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data) {
        bb_code = ret.result.data["bb_code"];
        var json = {
            "funName": "queryBbdcosttypeByBbid",
            "funSystem": "bx",
            "funType": "C",
            "valMap": {
                "bb_id": sfis_mainid
            }
        }
        var ret = webApi.ajax("system.common.queryList", json);
        if (ret && ret.status == "0" && ret.result && ret.result.data) {
            bbd_cost_type = ret.result.data[0]["bbd_cost_type"];
        }
    }
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": sfis_mainid,
            "status": "YSP",
            "approvor": "{userid}",
            "approval_date": "{strdatetime}"
        }
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret) {
        if (ret.status != "0") {
            dialogBox.showMessDialog("流程结束:" + ret.message);
        }
        if (bbd_cost_type == 'SPM') {
            zxFlowend(bb_code)
        }
    } else {
        dialogBox.showMessDialog("流程结束，审批状态失败!");
    }
    var json = {
        "funName": "BX_BILL",
        "funSystem": "bx",
        "valMap": {
            "bb_id": sfis_mainid
        }
    }
    var ret = webApi.ajax("system.common.queryForm", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data) {
        bb_code = ret.result.data["bb_code"];
        bbd_id = ret.result.data["bbd_id"];
        bxysData["bb_id"] = sfis_mainid;
        bxysData["bb_code"] = bb_code;
        bxysData["company_id"] = ret.result.data["company_id"];
        bxysData["enter_date"] = ret.result.data["enter_date"];  //单据日期
        bxysData["approval_date"] = ret.result.data["approval_date"];  //审核日期
    }
    var valList = new Array();
    var tempVal = getBillTypeInfo(bbd_id);
    var business_type_code = tempVal["business_type_code"];
    var reference_class = tempVal["reference_class"];
    ysSZ(valList, bxysData, business_type_code, reference_class)
}

//预算 实占
function ysSZ(valList, bxysData, business_type_code) {
    var flag = true;
    var json = {
        "method": "audit",
        "funSystem": "bx",
        "org_id": page.getCompanyId(),
        "zx_num": bxysData['bb_id'],      //当前单据ID
        "zx_code": bxysData['bb_code'],  //当前单据code
        "cbfd_code": business_type_code,     //业务类型编码
        "cbfd_source": "",  //来源控制类型
        "applycode": '',    //预算申请单号
        "applyid": '',   //预算申请单ID
        "zx_date": bxysData['enter_date'],  //执行单据日期
        "cbfl_auditdate": bxysData['approval_date'],   //审核日期
        "cbfl_period": "",  //所属期间
        "is_apply": "",
        "valList": ""
    }
    var ret = webApi.ajax("hcbm.WBbudgetControl.WBbudgetExcute", json);
    if (ret && ret.status == "0") {
        flag = true;
    } else {
        flag = false;
        dialogBox.showMessDialog(ret.message);
    }
    return flag;
}

//关闭流程弹框回调
function flowReturnBack() {
    window.location.reload();
}

//校验同行人
function checkTravelPartner(bb_id, bbd_id, is_check_travelpartner) {
    if ($("#appBxTravelPartnerList").length > 0 && is_check_travelpartner == "1" && $("#metting_count").length > 0) {
        var json = {
            "funName": "queryPartnerCount",
            "funSystem": "bx",
            "valMap": {
                "partner_bx_id": bb_id
            }
        }
        var ret = webApi.ajax("system.common.queryList", json).result.data[0];
        if (parseInt(ret.num) > 0) {
            var partnerNum = parseInt(ret.num) + 1;
        } else {
            var partnerNum = 1;
        }
        var persion_count = $("#metting_count").val();
        if (parseInt(partnerNum) != parseInt(persion_count)) {
            dialogBox.confirm("同行人信息与人数不匹配，请调整！", function () {
                page.openWindow("/html/common/Form.html?formCode=appTravelPartnerForm&bb_id=" + bb_id + "&bbd_id=" + bbd_id);
                return false;
            });
        } else {
            return true;
        }
    } else {
        return true;
    }
}

// 获取BBD_ID 单据类型
function getBBDID() {
    var bbd_id = $("#bbd_id").val();
    if (!page.isnotNull(bbd_id)) {
        bbd_id = page.getUrlParam("bbd_id");
    }
    return bbd_id;
}

//查看单据填报制度
function showTBZD() {
    var bbd_id = getBBDID();
    var json = {
        "funName": "queryAllBxFile",
        "funSystem": "sf",
        "valMap": {
            "_inmodel_id": bbd_id
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status && ret.result.data.length == 1) {
        var dataListStr = new Array();
        var ip = company + "/js/pdfjs/web/viewer.html?file=" + sitePath + "/" + ret.result.data[0].file_url + "&hideTitle=1";
        dataListStr.push(ip);
        page.sliderMethod("单据填报制度", dataListStr, "");
    } else {
        dialogBox.showMessDialog("未查询到单据填报制度文件！");
    }
}

function btnShowBraInfo() {
    var bb_id = $("#bb_id").val();
    var json = {
        "funName": "queryBRAinfoWithBBID",
        "funSystem": "bx",
        "valMap": {
            "bb_id": bb_id
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status == "0" && ret.result.data.length > 0) {
        var bra_ids = "";
        for (var i = 0; i < ret.result.data.length; i++) {
            bra_ids = bra_ids + "," + ret.result.data[i].bra_id;
        }
        page.openWindow("/html/Common/List.html?ListCode=bxBbLinkedBra&braids=" + bra_ids);
    } else {
        dialogBox.showMessDialog("当前单据未被报销单关联!");
    }
}

function inputFileUpload(fileConfigCode, fileDirectory, bandModelId, bandGroupId, ctrlId) {
    if (bandModelId.indexOf("{") > -1) {
        if (page.isnotNull(zc_bb_id)) {
            bandModelId = zc_bb_id;
        } else {
            zc_bra_id = page.getuuid();
            bandModelId = zc_bb_id;
        }
    }
    if ($("#" + ctrlId + "_upload_input").length <= 0) {
        dialogBox.showMessDialog("请选择上传文件", 2000);
        return;
    }
    var jsonData = {"fileConfigCode": fileConfigCode, "model_id": bandModelId, "group_id": bandGroupId};


    $.ajaxFileUpload({
        url: company + '/system/file/fileUpload',
        async: false, //是否是异步
        fileElementId: ctrlId + "_upload_input",
        data: {

            jsonStr: JSON.stringify(jsonData)
        },
        dataType: "text",
        success: function (data, status) {

            if (data) {
                //小程序申请单文件服务上传适配
                //var ret = JSON.parse(data);
                //if (ret.status == "0") {
                var ret = data;
                if (ret.indexOf('"status":"0"') != "-1") {
                    dialogBox.showMessDialog("上传成功!");
                    $("#" + ctrlId + "_upload_ul").empty();
                    var fileHtml = getFileLi(ctrlId, bandModelId, bandGroupId);
                    if (page.isnotNull(fileHtml)) {
                        $("#" + ctrlId + "_upload_ul").append(fileHtml);
                    }
                } else {
                    var message = ret.message;
                    dialogBox.showMessDialog("上传失败:" + message);
                }
            } else {
                dialogBox.showMessDialog("上传失败!");
            }
        },
        error: function (data, status, e) {
            dialogBox.alert("上传异常");
        }
    });
    dialogBox.showMessDialog("上传中请稍后...");
}

function getFileLi(ctrlId, bandModelId, bandGroupId) {
    var fileHtml = "";
    var json = {
        "funName": "queryFileByModelIdForPlatform",
        "funType": "C",
        "valMap": {
            "model_id": bandModelId,
            "group_id": bandGroupId
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
        var files = ret.result.data;

        for (var i = 0; i < files.length; i++) {
            var file_size = files[i].file_size;
            if (!page.isnotNull(file_size) || isNaN(file_size)) {
                file_size = 0;
            }
            var fileSize = parseInt(file_size / 1024) + "KB";
            var fileName = files[i].file_name;
            var fileId = files[i].file_id;
            var fileURL = files[i].file_url;
            var fileSuffix = files[i].file_suffix_name;
            // var URL = company + "/js/pdfjs/web/viewer.html?file=" + sitePath + "/" + fileURL;
            fileHtml += '<li><h4>' + fileName + '<span>' + fileSize + '</span></h4><div class="fileDiv">' +
                '<a id="' + ctrlId + '_upload_a_' + i + '" onclick="filePreView(\'' + bandModelId + '\',\'' + bandGroupId + '\',\'' + ctrlId + '\',\'' + i + '\',\'' + fileId + '\',\'' + fileSuffix + '\',\'' + fileURL + '\')">预览</a>' +
                '<span onclick="fileDelete(\'' + fileId + '\',\'' + ctrlId + '\',\'' + bandModelId + '\',\'' + bandGroupId + '\')"></span></div></li>';
        }//<a href="' + URL + '">预览</a>
    }
    return fileHtml;
}

//报销附件预览，支持上下切换
function filePreView(bandModelId, bandGroupId, ctrlId, index, fileId, suffix, file_url) {
    var dataListStr = new Array();//url集合
    var currURL = "";
    var json = {
        "funName": "queryAllBxFile",
        "funType": "C",
        "valMap": {
            "_inmodel_id": page.getUrlParam("bb_id")
        }
    }
    var ret = webApi.ajax("system.common.queryList", json);
    if (ret && ret.status == "0" && ret.result && ret.result.data && ret.result.data.length > 0) {
        var files = ret.result.data;
        for (var i = 0; i < files.length; i++) {
            var fileSuffix = files[i].file_suffix_name;
            if (fileSuffix == "pdf") {
                //var URL = company + "/js/pdfjs/web/viewer.html?file=" + sitePath + "/" + files[i].file_url + "&hideTitle=1";
                var URL = company + "/js/pdfjs/web/viewer.html?file_id=" + files[i].file_id + "&hideTitle=1";
                dataListStr.push(URL);
            } else if (fileSuffix == "jpg" || fileSuffix == "jpeg" || fileSuffix == "png") {
                var URL = company + "/system/file/filePreview?file_id=" + files[i].file_id;
                // var URL = company + "/html/common/imageView.html?file_id=" + files[i].file_id + "&hideTitle=1";
                dataListStr.push(URL);
            } else {
                dialogBox.showMessDialog("部分文件格式暂不支持预览!");
                break;
            }
        }
    }
    page.sliderMethod("预览", dataListStr, currURL);
}

/**
 * 新预算信息删除
 * @param _brcsdId
 */
function bxYSDel(_brcsdId) {
    if (!_brcsdId) {
        // dialogBox.showMessDialog("当前表单数据已发生变化，请刷新数据");
        return;
    }
    var _json = {
        "funName": "delBxBillCostById",
        "funType": "c",
        "valMap": {"bcsd_id": _brcsdId}
    };
    var _ret = webApi.ajax("system.common.submitForm", _json);
    if (_ret && _ret["status"] == "0") {
        dialogBox.showMessDialog("操作成功!")
        window.location.reload();
    } else {
        dialogBox.showMessDialog("删除失败!")
    }

}

/**
 * 修改金额弹出框
 */
function bxYSChangeBrcsdAmount(_brcsdId, _amount) {
    var status = $("#status").val();
    if (status != "YTJ" && status != "SPZ" && status != "YSP") {
        _amount = !!_amount ? _amount + "" : "0.00";
        _amount = _amount.replace(/\,/g, "");

        var amountHTML = "";
        amountHTML += '<div id="brcsdAmount" class="ticket">';
        amountHTML += '<ul class="ticketAlertBox">';
        amountHTML += '<li><span style="font-size:14px;">本次申请金额:<span></li>';
        amountHTML += '<li><input style="-webkit-user-select: text;-user-select: text;" id="amountInput" oninput="checkYSNum(this)" class="form-control applyAmount" value="' + _amount + '"></input></li>';
        amountHTML += '<li><button onclick="javascript:bxYSUpdateBrcsdAmount(\'' + _brcsdId + '\',\'' + _amount + '\')">确定</button><button onclick="javascript:closeDialog()">取消</button></li>';
        amountHTML += '</ul>';
        amountHTML += '</div>';
        $("body").append(amountHTML);
    } else {
        dialogBox.showMessDialog("当前状态不可修改");
    }
}

/**
 * 修改金额
 * @param _brcsdId
 * @param _amount
 */
function bxYSUpdateBrcsdAmount(_brcsdId, _amount) {
    var curAmount = $("#amountInput").val();
    if (isNaN(curAmount)) {
        dialogBox.showMessDialog("请输入正确的金额!");
        return;
    }
    if (curAmount == _amount) {
        dialogBox.showMessDialog("金额相等，无需修改!");
        return;
    }
    var _json = {
        "funName": "BX_COST_SHARE_DETAIL",
        "funSystem": "bx",
        "valMap": {
            "bcsd_id": _brcsdId,
            "brcsd_amount": curAmount
        }
    }
    var _ret = webApi.ajax("system.common.submitForm", _json);
    if (_ret && _ret["status"] == "0") {
        _json = {
            "funName": "queryBxsqShareInfo",
            "funType": "c",
            "valMap": {"bb_id": $("#bb_id").val()}
        };
        _ret = webApi.ajax("system.common.queryList", _json);
        if (_ret && _ret["status"] == "0") {
            var tableView = Form.getAppTablView("ywNewShareDetailList_appTable");
            tableView.rendTable(_ret["result"]["data"]);
            closeDialog();
        } else {
            window.location.reload();
        }
    } else {
        dialogBox.showMessDialog("更改金额失败!")
    }
}

function checkYSNum(ctlr) {
    var value = ctlr.value;
    if (isNaN(value)) {
        ctlr.value = "0.00";
        dialogBox.showMessDialog("请输入正确的数字!");
    }
}

/**
 * 关闭窗口
 */
function closeDialog() {
    $("#brcsdAmount").remove();
}


//2022.6.9 新预算接口校验（包含申请单和执行单校验）
function checkRefundBillYS(data) {
    var bb_code = data.bb_code;
    var bb_id = data.bb_id;
    var apply_date = data.enter_date; //单据日期
    var business_type_id = ""; //业务类型id
    var company_id = ""; //单位id
    var ysTableView = Form.getAppTablView("ywNewShareDetailList");
    var listData = new Array();
    var fundData = new Array();
    var ysDataList = ysTableView.getDataList();
    if (page.isnotNull(bb_code)) {
        _json = {
            "funName": "queryBillByCode",
            "funType": "c",
            "valMap": {"code": bb_code}
        };
        _ret = webApi.ajax("system.common.queryList", _json);
        if (_ret && _ret["status"] == "0") {
            business_type_id = _ret.result.data[0].bbd_id;
            company_id = _ret.result.data[0].company_id;
        }
    }
    for (var i = 0; i < ysDataList.length; i++) {
        var listMap = {};
        var fundMap = {};
        if (ysDataList[i].system_name == "预算管理") {
            listMap["system"] = "bm";
            fundMap["system"] = "bm";
        } else {
            listMap["system"] = "spm";
            fundMap["system"] = "spm";
        }
        listMap["budget_no"] = ysDataList[i].budget_no;
        listMap["expend_money"] = data.apply_amount;
        listMap["year"] = "";
        fundMap["budget_no"] = ysDataList[i].budget_no;
        fundMap["expend_money"] = data.apply_amount;
        fundMap["sys_datacode_id"] = ysDataList[i].sys_datacode_id;
        listData.push(listMap);
        if (page.isnotNull(ysDataList[i].sys_datacode_id)) {
            fundData.push(fundMap);
        }
    }
    var json = {
        "action": "applyCheck",
        "mainData": {
            "dj_no": bb_code,
            "dj_id": bb_id,
            "dj_time": apply_date,
            "bus_type_id": business_type_id,
            "company_id": company_id,
            "source_system": "bx"
        },
        "listData": listData,
        "fundData": fundData
    }
    var ret = webApi.ajax("fim.bxRefundAccount.saveRefundYs", json);
    if (ret && ret.status != "0") {
        if (ret.status == "-3" && ret.data.length > 0) {
            for (var i = 0; i < ret.data; i++) {
                if (ret.data[i].control_type == "2") {
                    // 预算提示控制
                    dialogBox.confirm(ret.message + ",是否继续执行？", function () {
                        var dataArray = saveData["data"];
                        var jsonData = dataArray[0];
                        jsonData["is_continue_cbms"] = "1";
                        _saveOperation(url, saveData, braId, isSubmit); // 继续提交
                    });
                } else {
                    dialogBox.showMessDialog(ret.message, 3000);
                    return false;
                }
            }
        } else {
            dialogBox.showMessDialog(ret.message, 3000);
            return false;
        }
    }
    for (var j = 0; j < ysDataList.length; j++) {
        if (ysDataList[j].system_name == "预算管理") {
            ysDataList[j].is_aboveys = "0";
            ysDataList[j].is_usable = "0"
        }
    }
    saveBxCostShareDB(data, ysDataList);
    return true;
}

//2022.6.10 新预算接口保存（包含申请单和执行单校验）
function saveRefundBillYS(data) {
    var bb_code = data.bb_code;
    var bb_id = data.bb_id;
    var apply_date = data.enter_date; //单据日期
    var business_type_id = ""; //业务类型id
    var company_id = ""; //单位id
    var ysTableView = Form.getAppTablView("ywNewShareDetailList");
    var listData = new Array();
    var fundData = new Array();
    if (page.isnotNull(bb_code)) {
        _json = {
            "funName": "queryBillByCode",
            "funType": "c",
            "valMap": {"code": bb_code}
        };
        _ret = webApi.ajax("system.common.queryList", _json);
        if (_ret && _ret["status"] == "0") {
            business_type_id = _ret.result.data[0].bbd_id;
            company_id = _ret.result.data[0].company_id;
        }
    }
    if (ysTableView) {
        var ysDataList = ysTableView.getDataList();
        for (var i = 0; i < ysDataList.length; i++) {
            var listMap = {};
            var fundMap = {};
            if (ysDataList[i].system_name == "预算管理") {
                listMap["system"] = "bm";
                fundMap["system"] = "bm";
            } else {
                listMap["system"] = "spm";
                fundMap["system"] = "spm";
            }
            listMap["budget_no"] = ysDataList[i].budget_no;
            listMap["expend_money"] = data.apply_amount;
            listMap["year"] = "";
            fundMap["budget_no"] = ysDataList[i].budget_no;
            fundMap["expend_money"] = data.apply_amount;
            fundMap["sys_datacode_id"] = ysDataList[i].sys_datacode_id;
            listData.push(listMap);
            if (page.isnotNull(ysDataList[i].sys_datacode_id)) {
                fundData.push(fundMap);
            }
        }
    }
    var json = {
        "action": "applySave",
        "mainData": {
            "dj_no": bb_code,
            "dj_id": bb_id,
            "dj_time": apply_date,
            "dj_preparer": data.user_id,
            "bus_type_id": business_type_id,
            "company_id": company_id,
            "source_system": "bx"
        },
        "listData": listData,
        "fundData": fundData
    }
    var ret = webApi.ajax("fim.bxRefundAccount.saveRefundYs", json);
    //执行单保存已测试保存成功、申请单保存已测试保存成功 ----------------------------------------------------
    if (ret && ret.status != "0") {
        dialogBox.showMessDialog(ret.message, 3000);
        return false;
    }
    return true;
}

function saveBxCostShareDB(reqData, data) {
    var valList = new Array();
    for (var i = 0; i < data.length; i++) {
        var valMap = {};
        valMap["bcsd_id"] = data[i].bcsd_id;
        valMap["is_over_budget"] = data[i].is_aboveys;
        valMap["brcsd_amount"] = reqData.apply_amount;
        valList.push(valMap);
    }
    var json = {
        "funName": "BX_COST_SHARE_DETAIL",
        "funSystem": "bx",
        "valList": valList,
        "funDbType": "update"
    }
    var ret = webApi.ajax("system.common.submitForm", json);
    if (ret && ret.status != "0") {
        dialogBox.showMessDialog(ret.message, 3000);
        return false;
    }
    return true;
}

// TODO ****************************************************************************

function setValue(ctrlId, value) {
    $("#" + ctrlId).val(value);
}

function initQueryConfigUrl(url) {
    return "fim.AppBill.QueryConfig";
}

function initQueryDataUrl(url) {
    return "fim.AppBill.Query";
}

function initDataSourceUrl(url) {
    return "fim.AppBill.DataSource";
}



